<template>
  <view v-if="currentStep != 'health-code'"
    class="bg-gradient-to-br from-[#4caf50] to-[#2e7d32] text-white p-[60rpx_40rpx_60rpx] text-center relative">
    <!-- <view class="text-[48rpx] font-bold flex items-center justify-center mb-[20rpx]">
      <IconFont name="heartbeat" class="mr-[20rpx] text-[56rpx]" />
      <text>健康中国</text>
    </view> -->
    <text class="text-[40rpx] mb-[40rpx] block" @tap="handleSign">{{ isHuaSheng ? '电子健康卡申请' : '诊疗卡申请' }}</text>
    <StepProgress
      :progressWidth="progressWidth"
      :step2Active="true"
      :step3Active="true"
      :handleCreateContract="handleCreateContract"
    />
  </view>
  <view class="min-h-[800rpx]">
    <StepHealthCode
      v-if="currentStep === 'health-code'"
      :code="code"
      :user="formData"
      :isHuaSheng="isHuaSheng"
      @reapply="reapply"
    />
    <StepStartSign
      v-else-if="currentStep === 'start-sign'"
      :contractName="contractName"
      :isHuaSheng="isHuaSheng"
      @sign="handleCreateContract"
    />
    <StepCompleteSign
      v-else-if="currentStep === 'complete-sign'"
      :status="status"
      :contractStatus="contractStatus"
      :contractName="contractName"
      @check="handleCheckAction"
      @resign="handleResign"
      :isHuaSheng="isHuaSheng"
    />
    <StepRegister
      v-else-if="currentStep === 'register'"
      :formData="formData"
      @update:formData="val => formData = val"
      @submit="handleRegister"
      @reapply="reapply"
      :isHuaSheng="isHuaSheng"
    />
    <StepSuccess
      v-else-if="currentStep === 'success'"
      @showCode="currentStep = 'health-code'"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { User, Hospital } from './types'
import Taro from '@tarojs/taro'
import { request } from '@/service/request';
import { IconFont } from '@nutui/icons-vue-taro'
import { localStg, PlatformUtils } from '@/utils';
import { useAuthStore } from '@/store';
import { CONTENT_TYPE } from '@/constants/service'
import { getContractTemplateByName, createContract, getHealthCode, registerHealthCode } from './tooler'
import StepRegister from './component/StepRegister.vue'
import StepStartSign from './component/StepStartSign.vue'
import StepCompleteSign from './component/StepCompleteSign.vue'
import StepSuccess from './component/StepSuccess.vue'
import StepHealthCode from './component/StepHealthCode.vue'
import StepProgress from './component/StepProgress.vue'
import { useGetAuthInfo } from '@/hooks';
import { AppName } from '@/constants';


const userStore = useAuthStore();
const currentStep = ref<'register' | 'start-sign' | 'complete-sign' | 'success' | 'health-code'>('')
const formData = ref<User>({
  name: userStore.nurseUser.name || '',
  idcard: userStore.nurseUser.idcard || '',
  phone: userStore.nurseUser.phone || '',
  vuid: userStore.nurseUser.vuid || ''
})
const code = ref('')
const hospital = ref<Hospital | null>(null)
let contractName = '健康码注册';
let templateData: any = null;
const status = ref('PENDING');
const isHuaSheng = computed(() => {
  // return userStore.nurseUser?.defaultHospitalName?.includes('华声');
  // return AppName == 'huasheng'
  return PlatformUtils.isHuaSheng();
});

// setTimeout(() => {
//   currentStep.value = 'register'
// }, 3000);

// 进度条等状态
const progressWidth = computed(() => {
  switch (currentStep.value) {
    case 'start-sign': return 0
    case 'complete-sign': return 50
    case 'register': return 80
    case 'success':
    case 'health-code': return 100
    default: return 0
  }
})

function reapply() {
  // currentStep.value = 'start-sign'
  // return;
  const curFamily = localStg.get("curFamily");
  if(curFamily){
    if(curFamily.relation != '1'){
      Taro.showToast({
        title: '请选择本人',
        icon: 'none',
        duration: 2000
      })
      return;
    }
  }

  if (!Taro.getStorageSync(contractName)) {
    currentStep.value = 'start-sign'
    return;
  }

  // 如果合同存在，检查合同是否签署
  currentStep.value = 'complete-sign'

}

const handleResign = () => {
  Taro.removeStorageSync(contractName)
  currentStep.value = 'start-sign'
}

const handleSign = () => {
  // handleSign
  request.post('/tencent_esign/tencent_contract/tencentContractInfo/getCreateConsoleLoginUrl', {
    operatorId: '1234567891',
    operatorName: "黎航",
    operatorTel: "15878776250",
    proxyOrganizationName: "南宁安好护理站",
    proxyOrganizationOpenId: "org_anfine2",
  }, {
    // contentType: CONTENT_TYPE.formUrlencoded,
    useErrMsg: true
  }).then((res: any) => {
    if (res.success) {
      // res.url
      // Taro.navigateTo({
      //   url: `/pages/webview/webview?url=${encodeURIComponent(res.success)}`
      // })
    }
    else {
      Taro.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }

  })
}

const curFamily = ref<any>(localStg.get("curFamily"));

onMounted(async () => {
  if(curFamily){
    console.log("curFamily", curFamily);
    formData.value = curFamily.value;
  }

  if(isHuaSheng.value){
    contractName = '健康码注册';
    Taro.setNavigationBarTitle({
      title: '电子健康码'
    })
  }
  else{
    contractName = '诊疗卡申请';
    Taro.setNavigationBarTitle({
      title: '诊疗卡'
    })
  }

  // if(!userStore.nurseUser.phone){
  //   Taro.showModal({
  //     title: '提示',
  //     content: '请先绑定手机号',
  //     showCancel: false,
  //     confirmText: '确定',
  //     success: function (res) {
  //       if (res.confirm) {
  //         Taro.navigateTo({ url: '/package-my/info/phone' })
  //       }
  //     }
  //   })
  //   return;
  // }
  // if(!userStore.nurseUser.idcard){
  //   Taro.showModal({
  //     title: '提示',
  //     content: '请先绑定身份证号',
  //     showCancel: false,
  //     confirmText: '确定',
  //     success: function (res) {
  //       if (res.confirm) {
  //         Taro.navigateTo({ url: '/package-my/info/idcard' })
  //       }
  //     }
  //   })
  //   return;
  // }
  const str = Taro.getStorageSync('defaultHospital');
  hospital.value = str ? JSON.parse(str) : null;
  initHealthCode();
})

async function initHealthCode() {

  if (!hospital.value?.operatorid) {
    Taro.showToast({
      title: '请先设置医院负责人',
      icon: 'none',
      duration: 2000
    })
    return;
  }

  templateData = await getContractTemplateByName(hospital.value, contractName)

  if(!templateData){
    Taro.showToast({
      title: '未找到合同模板',
      icon: 'none',
      duration: 2000
    })
    return;
  }

  if(isHuaSheng.value){
    await request.post('/health_code/healthCode/getToken', {}, { useErrMsg: true});
    if(userStore.nurseUser.vuid){
      currentStep.value = 'health-code'
      code.value = await getHealthCode(userStore.nurseUser);
      return;
    }
  }
  else{
    if(userStore.nurseUser.isVerify=='1'){
      currentStep.value = 'health-code'
      return;
    }
  }

  // 如果合同时间不存在，提示发起合同
  if (!Taro.getStorageSync(contractName)) {
    currentStep.value = 'start-sign'
    return;
  }

  // 如果合同时间存在，检查合同是否签署
  currentStep.value = 'complete-sign'

  const res = await checkContract();
  if (res) {
    currentStep.value = 'register'
  }
}

const contractStatus = ref('')


//检查合同是否签署
const checkContract = async () => {
  // /tencent_esign/tencent_flowstatuscallback/tencentFlowstatuscallbackInfo/queryById
  // /jeecg-boot/tencent_esign/tencent_contract/tencentContractInfo/list
  // tencent_esign/tencent_contract/tencentContractInfo/list
  const res:any = await request.get('/tencent_esign/tencent_flowstatuscallback/tencentFlowstatuscallbackInfo/list', {
    // "occurtime": Taro.getStorageSync(contractName + '_time'),
    // "approvenamea": userStore.nurseUser.name,
    // "proxyoperatoropenid": hospital.value?.operatorid,
    // "templateid": templateData?.templateId,
    // flowname: '健康码注册协议',
    // flowname: contractName,
    // pageSize: 100,

    // id: Taro.getStorageSync(contractName),
    flowid: Taro.getStorageSync(contractName),
  }, {
    useErrMsg: true
  })
  //重新请求用户数据
  useGetAuthInfo()

  if(res.success?.records?.length){
    const records = res.success.records;
    records.forEach((item:any)=>{
      status.value = item.approvestatusa;
      contractStatus.value = item.conStatus
    })
    return status.value == 'ACCEPT';
  }

  return false;
}

function handleCheckAction() {
  checkContract().then((res) => {
    if (res) {
      if(isHuaSheng.value){ 
        currentStep.value = 'register';
      }
      else{
        currentStep.value = 'health-code';
      }
      Taro.showToast({
        title: '电子合同签署成功！',
        icon: 'success',
        duration: 2000
      })
    }
    else {
      Taro.showToast({
        title: '电子合同未签署！',
        icon: 'none',
        duration: 2000
      })
    }
  })

  //添加一条监护人信息记录
  // addFamily()
}


function addFamily() {
    // const obj = userStore.nurseUser.nurseUserFamilyList.find((item: any) => item.relation == '1');
    // if (obj) {
    //     obj.name = userStore.nurseUser.name;
    //     obj.phone = userStore.nurseUser.phone;
    //     obj.idcard = userStore.nurseUser.idcard;
    // }
    // else {
    //     userStore.nurseUser.nurseUserFamilyList.push({
    //         name: userStore.nurseUser.name,
    //         // sex: "1",
    //         idcard: userStore.nurseUser.idcard,
    //         phone: userStore.nurseUser.phone,
    //         area: "",
    //         areaName: "",
    //         address: "",
    //         isSelf: "",
    //         age: "",
    //         ageUnit: "岁",
    //         relation: "1",
    //         relationName: "本人",
    //         record: "",
    //         hospital: "",
    //         hospitalName: "",
    //         dept: "",
    //         deptName: "",
    //         bed: "",
    //         bedName: "",
    //         status: "1",
    //         // id: "",
    //         userId: userStore.nurseUser.id
    //     });
    // }
    const obj = {
      name: userStore.nurseUser.name,
      // sex: "1",
      idcard: userStore.nurseUser.idcard,
      phone: userStore.nurseUser.phone,
      area: "",
      areaName: "",
      address: "",
      isSelf: "",
      age: "",
      ageUnit: "岁",
      relation: "1",
      relationName: "本人",
      record: "",
      hospital: "",
      hospitalName: "",
      dept: "",
      deptName: "",
      bed: "",
      bedName: "",
      status: "1",
      // id: "",
      userId: userStore.nurseUser.id
    }
    request.post('/nurse_user/nurseUser/addNurseUserFamily1', {
      ...obj
    }, {
      useErrMsg: true
    }).then((res: any) => {
      useGetAuthInfo()
    })

}

// 注册健康卡
function handleRegister() {
  registerHealthCode(userStore.nurseUser as any).then((res: any) => {
    if (res) {
      code.value = res;
      currentStep.value = "health-code"
      useGetAuthInfo()
    }
    else {
      Taro.showToast({
        title: '注册失败',
        icon: 'none',
        duration: 2000
      })
    }
  })

}

function handleCreateContract(params: any) {
  createContract({
    hospital: hospital.value,
    user: params || userStore.nurseUser,
    templateId: templateData.templateId,
    flowName: isHuaSheng.value ? "健康码注册协议" : "诊疗卡注册协议",
    flowDescription: isHuaSheng.value ? "健康码注册协议描述" : "诊疗卡注册协议描述",
  }).then((res: any) => {
    if (res.success) {
      currentStep.value = 'complete-sign'

      Taro.showToast({
        title: '电子合同已发送到您的手机，请及时签署！',
        icon: 'success',
        duration: 2000
      })
      Taro.setStorageSync(contractName, res.success.split(":").pop());

      addFamily()
    }
    else {
      Taro.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }

  })

}
</script>
